package com.macrounion.atv.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;
import com.macrounion.atv.cache.ChannelCache;
import com.macrounion.atv.cache.CurrentDataCache;
import com.macrounion.atv.cache.DeviceCache;
import com.macrounion.atv.cache.TrapRemoveCache;
import com.macrounion.atv.processor.ChannelProcessor;
import com.macrounion.atv.processor.CurrentDataProcessor;
import com.macrounion.atv.service.entity.Channel;
import com.macrounion.atv.service.entity.CurrentData;
import com.macrounion.atv.service.service.CurrentDataService;
import com.macrounion.base.service.utils.DateUtils;

/**
 * snmp协议数据刷新
 * @author Administrator
 *
 */
@Component
public class SnmpTrapRemoveTask {
	@Autowired
	private CurrentDataService currentDataService;
	@Autowired
	private TrapRemoveCache trapRemoveCache;
	@Autowired
	private CurrentDataProcessor currentDataProcessor;
	@Autowired
	private CurrentDataCache currentDataCache;
	@Autowired
	private ChannelProcessor channelProcessor;
	@Autowired
	private DeviceCache deviceCache;
	@Autowired
	private ChannelCache channelCache;
	
	@Scheduled(cron="0 0/1 * * * ? ")
	public void getData() {
		if(trapRemoveCache.getRemoved())
			return;
		List<CurrentData> datas = currentDataService.getSnmpTraps();
		if(CollectionUtils.isEmpty(datas)) {
			trapRemoveCache.saveRemoved(true);
			return;
		}
		List<CurrentData> removes = datas.parallelStream().filter(d->{return d.getCreatedTime().before(DateUtils.addMinute(new Date(), -5));}).collect(Collectors.toList());
		if(CollectionUtils.isEmpty(removes)) {
			return;
		}
		List<String> deviceIds = Lists.newArrayList();
		//告警恢复
		removes.forEach(r->{
			currentDataProcessor.remove(r);
			if(!deviceIds.contains(r.getDeviceId()) && r.getDeviceId() != null);
				deviceIds.add(r.getDeviceId());
			try {
				Channel c = channelCache.getChannel(r.getDeviceId(), r.getChannelCode());
				r.setAlarm(0);//恢复
				channelProcessor.sendTarpToItu(deviceCache.getDevice(r.getDeviceCode()), c, r);
			} catch (Exception e) {
				// TODO: handle exception
			}
		});
		deviceIds.forEach(deviceId->{
			List<CurrentData> rs = removes.parallelStream().filter(r->{return r.getDeviceId() != null && r.getDeviceId().equals(deviceId); }).collect(Collectors.toList());
			List<CurrentData> full = new ArrayList<CurrentData>(currentDataCache.getCurrentData(deviceId));
			if(!CollectionUtils.isEmpty(rs) && !CollectionUtils.isEmpty(full)) {
				currentDataCache.removeInCacheList(deviceId,rs,full);
			}
		});
	}

	

	
}
